<template>
  <div class="proportion-progress-bar">
    <!-- 可视化分佣比例展示 -->
    <div class="proportion-visualization">
      <div class="visual-title" v-if="title">
        <i class="el-icon-data-line"></i>
        {{ title }}
      </div>
      <!-- 外层进度条：根据模式显示不同的字段 -->
      <div class="outer-progress-container">
        <div class="progress-labels">
          <span class="progress-label">总公司：{{ innerValues.company }}%</span>
          <span class="progress-label">区域代理：{{ innerValues.agent }}%</span>
          <span class="progress-label">商家：{{ innerValues.merchant }}%</span>
          <span class="progress-label" v-if="mode === 'ad'">用户：{{ innerValues.user }}%</span>
          <span class="progress-label" v-if="mode === 'alliance' && innerValues.merchant > 0">业务员：{{ (innerValues.merchant * innerValues.salesman / 100).toFixed(2) }}%</span>
          <span class="progress-total" :class="{ 'text-danger': totalPercentage !== 100, 'text-success': totalPercentage === 100 }">
            合计：{{ totalPercentage }}%
          </span>
        </div>
        <div
          class="outer-progress-bar"
          ref="outerProgressBar"
          @mousemove="handleOuterProgressMouseMove"
          @mouseup="handleOuterProgressMouseUp"
          @mouseleave="handleOuterProgressMouseUp">
          <!-- 总公司 -->
          <div
            class="progress-segment company-segment"
            :style="{ width: innerValues.company + '%' }"
            :title="`总公司：${innerValues.company}%`">
            <span class="segment-label" v-if="innerValues.company >= 5">{{ innerValues.company }}%</span>
          </div>
          <!-- 公司/代理分割点 -->
          <div
            v-if="innerValues.company > 0 && innerValues.agent > 0"
            class="drag-handle outer-drag-handle"
            :style="{ left: innerValues.company + '%' }"
            @mousedown.prevent="startDragOuter($event, 'company-agent')"
            :title="'拖动调整总公司和区域代理比例'">
            <div class="drag-handle-bar"></div>
          </div>
          <!-- 区域代理 -->
          <div
            class="progress-segment agent-segment"
            :style="{ width: innerValues.agent + '%' }"
            :title="`区域代理：${innerValues.agent}%`">
            <span class="segment-label" v-if="innerValues.agent >= 5">{{ innerValues.agent }}%</span>
          </div>
          <!-- 代理/商家分割点 -->
          <div
            v-if="innerValues.agent > 0 && innerValues.merchant > 0"
            class="drag-handle outer-drag-handle"
            :style="{ left: (innerValues.company + innerValues.agent) + '%' }"
            @mousedown.prevent="startDragOuter($event, 'agent-merchant')"
            :title="'拖动调整区域代理和商家比例'">
            <div class="drag-handle-bar"></div>
          </div>
          <!-- 商家（异业联盟模式包含嵌套进度条，广告模式为普通进度条） -->
          <div
            class="progress-segment merchant-segment"
            :style="{ width: innerValues.merchant + '%' }"
            :title="`商家：${innerValues.merchant}%`">
            <!-- 当商家比例较大且内层业务员比例较小时，显示外层标签（仅异业联盟模式） -->
            <span class="segment-label" v-if="mode === 'alliance' && innerValues.merchant >= 15 && (innerValues.merchant * innerValues.salesman / 100 < 5 || innerValues.salesman < 20)">{{ innerValues.merchant }}%</span>
            <!-- 广告模式：显示商家标签 -->
            <span class="segment-label" v-if="mode === 'ad' && innerValues.merchant >= 5">{{ innerValues.merchant }}%</span>
            <!-- 异业联盟无业务员模式：显示商家标签 -->
            <span class="segment-label" v-if="mode === 'alliance-no-salesman' && innerValues.merchant >= 5">{{ innerValues.merchant }}%</span>
            <!-- 嵌套进度条：业务员 + 商家剩余（仅异业联盟/商家本店消费模式） -->
            <div
              class="inner-progress-bar"
              v-if="mode === 'alliance' && innerValues.merchant > 0"
              ref="innerProgressBar"
              @mousemove="handleInnerProgressMouseMove"
              @mouseup="handleInnerProgressMouseUp"
              @mouseleave="handleInnerProgressMouseUp">
              <!-- 商家剩余 -->
              <div
                class="inner-segment merchant-remain-segment"
                :style="{ width: (100 - innerValues.salesman) + '%' }"
                :title="`商家剩余：${(innerValues.merchant * (100 - innerValues.salesman) / 100).toFixed(2)}%`">
              </div>
              <!-- 业务员/商家剩余分割点 -->
              <div
                v-if="innerValues.salesman >= 1 && innerValues.salesman < 99"
                class="drag-handle inner-drag-handle"
                :style="{ left: (100 - innerValues.salesman) + '%' }"
                @mousedown.prevent="startDragInner($event)"
                :title="'拖动调整业务员在商家分佣中的比例'">
                <div class="drag-handle-bar"></div>
              </div>
              <!-- 业务员 -->
              <div
                class="inner-segment salesman-segment"
                :style="{ width: innerValues.salesman + '%' }"
                :title="`业务员：${(innerValues.merchant * innerValues.salesman / 100).toFixed(2)}%`">
                <span class="inner-label" v-if="innerValues.salesman >= 15">{{ innerValues.salesman }}%</span>
              </div>
            </div>
          </div>
          <!-- 商家/用户分割点（仅广告模式） -->
          <div
            v-if="mode === 'ad' && innerValues.merchant > 0 && innerValues.user > 0"
            class="drag-handle outer-drag-handle"
            :style="{ left: (innerValues.company + innerValues.agent + innerValues.merchant) + '%' }"
            @mousedown.prevent="startDragOuter($event, 'merchant-user')"
            :title="'拖动调整商家和用户比例'">
            <div class="drag-handle-bar"></div>
          </div>
          <!-- 用户（仅广告模式） -->
          <div
            v-if="mode === 'ad'"
            class="progress-segment user-segment"
            :style="{ width: innerValues.user + '%' }"
            :title="`用户：${innerValues.user}%`">
            <span class="segment-label" v-if="innerValues.user >= 5">{{ innerValues.user }}%</span>
          </div>
        </div>
        <!-- 商家内部说明（仅异业联盟/商家本店消费模式） -->
        <div class="merchant-detail" v-if="mode === 'alliance' && innerValues.merchant > 0">
          <div class="detail-item">
            <span class="detail-color merchant-remain-color"></span>
            <span class="detail-text">商家剩余：{{ (innerValues.merchant * (100 - innerValues.salesman) / 100).toFixed(2) }}%</span>
          </div>
          <div class="detail-item">
            <span class="detail-color salesman-color"></span>
            <span class="detail-text">业务员：{{ (innerValues.merchant * innerValues.salesman / 100).toFixed(2) }}%（从商家分佣的{{ innerValues.salesman }}%中获得）</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ProportionProgressBar',
  props: {
    // 比例值对象
    value: {
      type: Object,
      required: true,
      default: () => ({
        company: 40,     // 总公司
        agent: 25,       // 区域代理
        salesman: 30,    // 业务员（在商家分佣中的比例，仅异业联盟模式）
        merchant: 20,    // 商家
        user: 15         // 用户（仅广告模式）
      })
    },
    // 标题
    title: {
      type: String,
      default: '分佣比例可视化'
    },
    // 模式：'alliance' 异业联盟/商家本店消费（3字段+嵌套业务员） | 'alliance-no-salesman' 异业联盟无业务员（3字段） | 'ad' 广告（4字段）
    mode: {
      type: String,
      default: 'alliance',
      validator: (value) => ['alliance', 'alliance-no-salesman', 'ad'].includes(value)
    }
  },
  data() {
    return {
      // 内部维护的值
      innerValues: {
        company: 40,
        agent: 25,
        salesman: 30,
        merchant: 20,
        user: 15
      },
      // 拖动状态
      dragState: {
        isDragging: false,
        dragType: null, // 'outer-company-agent' | 'outer-agent-merchant' | 'inner-salesman' | 'outer-merchant-user'
        startX: 0,
        startValues: {}
      }
    }
  },
  computed: {
    // 分佣总和百分比
    totalPercentage() {
      if (this.mode === 'ad') {
        // 广告模式：4个字段相加
        return this.innerValues.company + this.innerValues.agent + this.innerValues.merchant + this.innerValues.user
      } else if (this.mode === 'alliance-no-salesman') {
        // 异业联盟无业务员模式：3个字段相加
        return this.innerValues.company + this.innerValues.agent + this.innerValues.merchant
      } else {
        // 异业联盟/商家本店消费模式：业务员分佣从商家分佣中获取，不参与总分计算
        return this.innerValues.company + this.innerValues.agent + this.innerValues.merchant
      }
    }
  },
  watch: {
    // 监听外部传入的值变化
    value: {
      handler(newVal) {
        if (newVal) {
          this.innerValues = {
            company: newVal.company || 40,
            agent: newVal.agent || 25,
            salesman: newVal.salesman || 30,
            merchant: newVal.merchant || 20,
            user: newVal.user || 15
          }
          // 确保总和为100%
          this.normalizeTo100()
        }
      },
      immediate: true,
      deep: true
    },
    // 监听总和变化，确保始终为100%
    totalPercentage: {
      handler(newVal) {
        if (Math.abs(newVal - 100) > 0.01) {
          this.normalizeTo100()
        }
      }
    }
  },
  methods: {
    // 规范化总和为100%
    normalizeTo100() {
      const currentTotal = this.totalPercentage
      if (Math.abs(currentTotal - 100) < 0.01) {
        return // 已经是100%，无需调整
      }

      if (this.mode === 'ad') {
        // 广告模式：4个字段
        const total = this.innerValues.company + this.innerValues.agent + this.innerValues.merchant + this.innerValues.user
        if (total > 0) {
          const ratio = 100 / total
          this.innerValues.company = Math.max(1, Math.round(this.innerValues.company * ratio))
          this.innerValues.agent = Math.max(1, Math.round(this.innerValues.agent * ratio))
          this.innerValues.merchant = Math.max(1, Math.round(this.innerValues.merchant * ratio))
          this.innerValues.user = Math.max(1, Math.round(this.innerValues.user * ratio))

          // 再次检查并微调以确保总和为100%
          const newTotal = this.innerValues.company + this.innerValues.agent + this.innerValues.merchant + this.innerValues.user
          const diff = 100 - newTotal
          if (diff !== 0) {
            // 将差额加到最大的字段上
            if (this.innerValues.company >= this.innerValues.agent &&
                this.innerValues.company >= this.innerValues.merchant &&
                this.innerValues.company >= this.innerValues.user) {
              this.innerValues.company += diff
            } else if (this.innerValues.agent >= this.innerValues.merchant &&
                       this.innerValues.agent >= this.innerValues.user) {
              this.innerValues.agent += diff
            } else if (this.innerValues.merchant >= this.innerValues.user) {
              this.innerValues.merchant += diff
            } else {
              this.innerValues.user += diff
            }
          }
        }
      } else if (this.mode === 'alliance-no-salesman') {
        // 异业联盟无业务员模式：3个字段
        const total = this.innerValues.company + this.innerValues.agent + this.innerValues.merchant
        if (total > 0) {
          const ratio = 100 / total
          this.innerValues.company = Math.max(1, Math.round(this.innerValues.company * ratio))
          this.innerValues.agent = Math.max(1, Math.round(this.innerValues.agent * ratio))
          this.innerValues.merchant = Math.max(1, Math.round(this.innerValues.merchant * ratio))

          // 再次检查并微调以确保总和为100%
          const newTotal = this.innerValues.company + this.innerValues.agent + this.innerValues.merchant
          const diff = 100 - newTotal
          if (diff !== 0) {
            // 将差额加到最大的字段上
            if (this.innerValues.company >= this.innerValues.agent &&
                this.innerValues.company >= this.innerValues.merchant) {
              this.innerValues.company += diff
            } else if (this.innerValues.agent >= this.innerValues.merchant) {
              this.innerValues.agent += diff
            } else {
              this.innerValues.merchant += diff
            }
          }
        }
      } else {
        // 异业联盟/商家本店消费模式：3个字段（业务员不参与总分计算）
        const total = this.innerValues.company + this.innerValues.agent + this.innerValues.merchant
        if (total > 0) {
          const ratio = 100 / total
          this.innerValues.company = Math.max(1, Math.round(this.innerValues.company * ratio))
          this.innerValues.agent = Math.max(1, Math.round(this.innerValues.agent * ratio))
          this.innerValues.merchant = Math.max(1, Math.round(this.innerValues.merchant * ratio))

          // 再次检查并微调以确保总和为100%
          const newTotal = this.innerValues.company + this.innerValues.agent + this.innerValues.merchant
          const diff = 100 - newTotal
          if (diff !== 0) {
            // 将差额加到最大的字段上
            if (this.innerValues.company >= this.innerValues.agent &&
                this.innerValues.company >= this.innerValues.merchant) {
              this.innerValues.company += diff
            } else if (this.innerValues.agent >= this.innerValues.merchant) {
              this.innerValues.agent += diff
            } else {
              this.innerValues.merchant += diff
            }
          }
        }
      }
    },

    // 开始拖动外层进度条
    startDragOuter(event, type) {
      this.dragState.isDragging = true
      this.dragState.dragType = 'outer-' + type
      this.dragState.startX = event.clientX
      const startValues = {
        company: this.innerValues.company,
        agent: this.innerValues.agent,
        merchant: this.innerValues.merchant
      }
      // 广告模式还需要记录user
      if (this.mode === 'ad') {
        startValues.user = this.innerValues.user
      }
      this.dragState.startValues = startValues
      document.addEventListener('mousemove', this.handleDocumentMouseMove)
      document.addEventListener('mouseup', this.handleDocumentMouseUp)
      document.body.style.cursor = 'col-resize'
      document.body.style.userSelect = 'none'
    },

    // 开始拖动内层进度条
    startDragInner(event) {
      this.dragState.isDragging = true
      this.dragState.dragType = 'inner-salesman'
      this.dragState.startX = event.clientX
      this.dragState.startValues = {
        salesman: this.innerValues.salesman
      }
      document.addEventListener('mousemove', this.handleDocumentMouseMove)
      document.addEventListener('mouseup', this.handleDocumentMouseUp)
      document.body.style.cursor = 'col-resize'
      document.body.style.userSelect = 'none'
    },

    // 处理文档鼠标移动（外层进度条）
    handleOuterProgressMouseMove(event) {
      if (!this.dragState.isDragging || !this.dragState.dragType.startsWith('outer-')) {
        return
      }
      this.handleDragMove(event)
    },

    // 处理文档鼠标移动（内层进度条）
    handleInnerProgressMouseMove(event) {
      if (!this.dragState.isDragging || this.dragState.dragType !== 'inner-salesman') {
        return
      }
      this.handleDragMove(event)
    },

    // 处理拖动移动
    handleDragMove(event) {
      if (!this.dragState.isDragging) return

      const deltaX = event.clientX - this.dragState.startX

      if (this.dragState.dragType === 'outer-company-agent') {
        // 拖动公司/代理分割点：只调整公司和代理
        const progressBar = this.$refs.outerProgressBar
        if (!progressBar) return

        const barWidth = progressBar.offsetWidth
        const deltaPercent = (deltaX / barWidth) * 100

        if (this.mode === 'ad') {
          // 广告模式：商家和用户保持不变
          const merchantFixed = Math.max(1, this.dragState.startValues.merchant)
          const userFixed = Math.max(1, this.dragState.startValues.user)
          const available = 100 - merchantFixed - userFixed

          let newCompany = this.dragState.startValues.company + deltaPercent
          let newAgent = this.dragState.startValues.agent - deltaPercent

          // 限制在可用范围内，且每个不能小于1%
          if (newCompany < 1) {
            newCompany = 1
            newAgent = Math.max(1, available - newCompany)
          } else if (newCompany > available - 1) {
            newCompany = Math.max(1, available - 1)
            newAgent = 1
          } else {
            if (newAgent < 1) {
              newAgent = 1
              newCompany = Math.max(1, available - 1)
            }
          }

          this.innerValues.company = Math.round(newCompany)
          this.innerValues.agent = Math.round(newAgent)
          this.innerValues.merchant = Math.round(merchantFixed)
          this.innerValues.user = Math.round(userFixed)
        } else if (this.mode === 'alliance-no-salesman') {
          // 异业联盟无业务员模式：商家比例保持不变（最小1%）
          const merchantFixed = Math.max(1, this.dragState.startValues.merchant)
          // 可用的比例空间（公司和代理）
          const available = 100 - merchantFixed

          // 计算新的公司和代理比例
          let newCompany = this.dragState.startValues.company + deltaPercent
          let newAgent = this.dragState.startValues.agent - deltaPercent

          // 限制在可用范围内，且每个不能小于1%
          if (newCompany < 1) {
            newCompany = 1
            newAgent = Math.max(1, available - newCompany)
          } else if (newCompany > available - 1) {
            newCompany = Math.max(1, available - 1)
            newAgent = 1
          } else {
            // 确保代理也不小于1%
            if (newAgent < 1) {
              newAgent = 1
              newCompany = Math.max(1, available - 1)
            } else if (newCompany < 1) {
              newCompany = 1
              newAgent = Math.max(1, available - 1)
            }
          }

          // 更新值，商家保持不变
          this.innerValues.company = Math.round(newCompany)
          this.innerValues.agent = Math.round(newAgent)
          this.innerValues.merchant = Math.round(merchantFixed)
        } else {
          // 异业联盟/商家本店消费模式：商家比例保持不变（最小1%）
          const merchantFixed = Math.max(1, this.dragState.startValues.merchant)
          // 可用的比例空间（公司和代理）
          const available = 100 - merchantFixed

          // 计算新的公司和代理比例
          let newCompany = this.dragState.startValues.company + deltaPercent
          let newAgent = this.dragState.startValues.agent - deltaPercent

          // 限制在可用范围内，且每个不能小于1%
          if (newCompany < 1) {
            newCompany = 1
            newAgent = Math.max(1, available - newCompany)
          } else if (newCompany > available - 1) {
            newCompany = Math.max(1, available - 1)
            newAgent = 1
          } else {
            // 确保代理也不小于1%
            if (newAgent < 1) {
              newAgent = 1
              newCompany = Math.max(1, available - 1)
            } else if (newCompany < 1) {
              newCompany = 1
              newAgent = Math.max(1, available - 1)
            }
          }

          // 更新值，商家保持不变
          this.innerValues.company = Math.round(newCompany)
          this.innerValues.agent = Math.round(newAgent)
          this.innerValues.merchant = Math.round(merchantFixed)
        }
      } else if (this.dragState.dragType === 'outer-agent-merchant') {
        // 拖动代理/商家分割点：只调整代理和商家
        const progressBar = this.$refs.outerProgressBar
        if (!progressBar) return

        const barWidth = progressBar.offsetWidth
        const deltaPercent = (deltaX / barWidth) * 100

        if (this.mode === 'ad') {
          // 广告模式：公司和用户保持不变
          const companyFixed = Math.max(1, this.dragState.startValues.company)
          const userFixed = Math.max(1, this.dragState.startValues.user)
          const available = 100 - companyFixed - userFixed

          let newAgent = this.dragState.startValues.agent + deltaPercent
          let newMerchant = this.dragState.startValues.merchant - deltaPercent

          // 限制在可用范围内，且每个不能小于1%
          if (newAgent < 1) {
            newAgent = 1
            newMerchant = Math.max(1, available - newAgent)
          } else if (newAgent > available - 1) {
            newAgent = Math.max(1, available - 1)
            newMerchant = 1
          } else {
            if (newMerchant < 1) {
              newMerchant = 1
              newAgent = Math.max(1, available - 1)
            }
          }

          this.innerValues.company = Math.round(companyFixed)
          this.innerValues.agent = Math.round(newAgent)
          this.innerValues.merchant = Math.round(newMerchant)
          this.innerValues.user = Math.round(userFixed)
        } else if (this.mode === 'alliance-no-salesman') {
          // 异业联盟无业务员模式：公司比例保持不变（最小1%）
          const companyFixed = Math.max(1, this.dragState.startValues.company)
          // 可用的比例空间（代理和商家）
          const available = 100 - companyFixed

          // 计算新的代理和商家比例
          let newAgent = this.dragState.startValues.agent + deltaPercent
          let newMerchant = this.dragState.startValues.merchant - deltaPercent

          // 限制在可用范围内，且每个不能小于1%
          if (newAgent < 1) {
            newAgent = 1
            newMerchant = Math.max(1, available - newAgent)
          } else if (newAgent > available - 1) {
            newAgent = Math.max(1, available - 1)
            newMerchant = 1
          } else {
            // 确保商家也不小于1%
            if (newMerchant < 1) {
              newMerchant = 1
              newAgent = Math.max(1, available - 1)
            } else if (newAgent < 1) {
              newAgent = 1
              newMerchant = Math.max(1, available - 1)
            }
          }

          // 更新值，公司保持不变
          this.innerValues.agent = Math.round(newAgent)
          this.innerValues.merchant = Math.round(newMerchant)
          this.innerValues.company = Math.round(companyFixed)
        } else {
          // 异业联盟/商家本店消费模式：公司比例保持不变（最小1%）
          const companyFixed = Math.max(1, this.dragState.startValues.company)
          // 可用的比例空间（代理和商家）
          const available = 100 - companyFixed

          // 计算新的代理和商家比例
          let newAgent = this.dragState.startValues.agent + deltaPercent
          let newMerchant = this.dragState.startValues.merchant - deltaPercent

          // 限制在可用范围内，且每个不能小于1%
          if (newAgent < 1) {
            newAgent = 1
            newMerchant = Math.max(1, available - newAgent)
          } else if (newAgent > available - 1) {
            newAgent = Math.max(1, available - 1)
            newMerchant = 1
          } else {
            // 确保商家也不小于1%
            if (newMerchant < 1) {
              newMerchant = 1
              newAgent = Math.max(1, available - 1)
            } else if (newAgent < 1) {
              newAgent = 1
              newMerchant = Math.max(1, available - 1)
            }
          }

          // 更新值，公司保持不变
          this.innerValues.agent = Math.round(newAgent)
          this.innerValues.merchant = Math.round(newMerchant)
          this.innerValues.company = Math.round(companyFixed)
        }
      } else if (this.dragState.dragType === 'inner-salesman') {
        // 拖动业务员比例（商家内部）
        const progressBar = this.$refs.innerProgressBar
        if (!progressBar) return

        const barWidth = progressBar.offsetWidth
        if (barWidth === 0) return

        const deltaPercent = (deltaX / barWidth) * 100

        // 业务员比例：向右拖动减少，向左拖动增加
        // 最小1%，最大99%（确保商家剩余也至少有1%）
        const newSalesman = Math.max(1, Math.min(99, this.dragState.startValues.salesman - deltaPercent))
        this.innerValues.salesman = Math.round(newSalesman)
      } else if (this.dragState.dragType === 'outer-merchant-user') {
        // 拖动商家/用户分割点（仅广告模式）：只调整商家和用户，公司和代理保持不变
        const progressBar = this.$refs.outerProgressBar
        if (!progressBar) return

        const barWidth = progressBar.offsetWidth
        const deltaPercent = (deltaX / barWidth) * 100

        // 公司和代理比例保持不变（最小1%）
        const companyFixed = Math.max(1, this.dragState.startValues.company)
        const agentFixed = Math.max(1, this.dragState.startValues.agent)
        // 可用的比例空间（商家和用户）
        const available = 100 - companyFixed - agentFixed

        // 计算新的商家和用户比例
        let newMerchant = this.dragState.startValues.merchant + deltaPercent
        let newUser = this.dragState.startValues.user - deltaPercent

        // 限制在可用范围内，且每个不能小于1%
        if (newMerchant < 1) {
          newMerchant = 1
          newUser = Math.max(1, available - newMerchant)
        } else if (newMerchant > available - 1) {
          newMerchant = Math.max(1, available - 1)
          newUser = 1
        } else {
          // 确保用户也不小于1%
          if (newUser < 1) {
            newUser = 1
            newMerchant = Math.max(1, available - 1)
          } else if (newMerchant < 1) {
            newMerchant = 1
            newUser = Math.max(1, available - 1)
          }
        }

        // 更新值，公司和代理保持不变
        this.innerValues.company = Math.round(companyFixed)
        this.innerValues.agent = Math.round(agentFixed)
        this.innerValues.merchant = Math.round(newMerchant)
        this.innerValues.user = Math.round(newUser)
      }
    },

    // 处理文档鼠标移动
    handleDocumentMouseMove(event) {
      if (this.dragState.dragType && this.dragState.dragType.startsWith('outer-')) {
        this.handleDragMove(event)
      } else if (this.dragState.dragType === 'inner-salesman') {
        this.handleDragMove(event)
      }
    },

    // 处理外层进度条鼠标抬起
    handleOuterProgressMouseUp() {
      this.endDrag()
    },

    // 处理内层进度条鼠标抬起
    handleInnerProgressMouseUp() {
      this.endDrag()
    },

    // 处理文档鼠标抬起
    handleDocumentMouseUp() {
      this.endDrag()
    },

    // 结束拖动 - 触发change事件，传递所有比例值
    endDrag() {
      if (this.dragState.isDragging) {
        this.dragState.isDragging = false
        this.dragState.dragType = null
        this.dragState.startX = 0
        this.dragState.startValues = {}
        document.removeEventListener('mousemove', this.handleDocumentMouseMove)
        document.removeEventListener('mouseup', this.handleDocumentMouseUp)
        document.body.style.cursor = ''
        document.body.style.userSelect = ''

        // 拖动结束时，触发change事件，传递包含所有比例的对象
        const changeData = {
          company: this.innerValues.company,
          agent: this.innerValues.agent,
          merchant: this.innerValues.merchant,
          total: this.totalPercentage
        }
        // 根据模式添加不同的字段
        if (this.mode === 'ad') {
          changeData.user = this.innerValues.user
        } else if (this.mode === 'alliance') {
          changeData.salesman = this.innerValues.salesman
        }
        // alliance-no-salesman 模式不需要额外字段

        // 确保总和为100%后再触发change事件
        this.normalizeTo100()

        // 重新构建changeData以确保数据准确
        const finalChangeData = {
          company: this.innerValues.company,
          agent: this.innerValues.agent,
          merchant: this.innerValues.merchant,
          total: this.totalPercentage
        }
        if (this.mode === 'ad') {
          finalChangeData.user = this.innerValues.user
        } else if (this.mode === 'alliance') {
          finalChangeData.salesman = this.innerValues.salesman
        }

        this.$emit('change', finalChangeData)
      }
    }
  },
  beforeDestroy() {
    // 清理事件监听器
    document.removeEventListener('mousemove', this.handleDocumentMouseMove)
    document.removeEventListener('mouseup', this.handleDocumentMouseUp)
  }
}
</script>

<style scoped>
.proportion-progress-bar {
  width: 100%;
}

/* 分佣比例可视化样式 */
.proportion-visualization {
  height: 100%;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border: 1px solid #e9ecef;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: visible;
}

.visual-title {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.visual-title i {
  margin-right: 8px;
  font-size: 18px;
  color: #409eff;
}

.outer-progress-container {
  width: 100%;
  overflow: visible;
}

.progress-labels {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  flex-wrap: wrap;
  gap: 8px;
}

.progress-label {
  font-size: 13px;
  color: #606266;
  font-weight: 500;
}

.progress-total {
  font-size: 14px;
  font-weight: 600;
  padding: 4px 12px;
  border-radius: 4px;
  background: #f0f2f5;
}

.progress-total.text-success {
  color: #67c23a;
  background: #f0f9ff;
}

.progress-total.text-danger {
  color: #f56c6c;
  background: #fef0f0;
}

.outer-progress-bar {
  display: flex;
  width: 100%;
  height: 48px;
  background: #f0f2f5;
  border-radius: 8px;
  overflow: visible;
  border: 2px solid #e4e7ed;
  position: relative;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.06);
}

.progress-segment {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  transition: all 0.3s ease;
  min-width: 0;
  border-right: 1px solid rgba(255, 255, 255, 0.3);
  overflow: visible;
}

.progress-segment:last-child {
  border-right: none;
}

.company-segment {
  background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
}

.agent-segment {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
}

.merchant-segment {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
  position: relative;
}

.user-segment {
  background: linear-gradient(135deg, #909399 0%, #b1b3b8 100%);
}

.segment-label {
  color: #ffffff;
  font-size: 14px;
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
  white-space: nowrap;
  z-index: 10;
}

/* 嵌套进度条（商家内部） */
.inner-progress-bar {
  position: absolute;
  top: 2px;
  left: 2px;
  right: 2px;
  bottom: 2px;
  display: flex;
  border-radius: 4px;
  overflow: visible;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.inner-segment {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  transition: all 0.3s ease;
}

.merchant-remain-segment {
  background: rgba(103, 194, 58, 0.85);
}

.salesman-segment {
  background: linear-gradient(135deg, #e6a23c 0%, #ebb563 100%);
  border-left: 1px solid rgba(255, 255, 255, 0.3);
}

.inner-label {
  color: #ffffff;
  font-size: 11px;
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  white-space: nowrap;
  z-index: 10;
}

/* 拖动手柄样式 */
.drag-handle {
  position: absolute;
  top: -4px;
  bottom: -4px;
  width: 8px;
  margin-left: -4px;
  z-index: 100;
  cursor: col-resize;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.drag-handle:hover {
  width: 12px;
  margin-left: -6px;
}

.drag-handle:hover .drag-handle-bar {
  width: 100%;
  background: #409eff;
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.6);
}

.drag-handle-bar {
  width: 4px;
  height: 100%;
  background: rgba(255, 255, 255, 0.8);
  border: 2px solid #409eff;
  border-radius: 2px;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.3);
  transition: all 0.2s ease;
}

.outer-drag-handle {
  top: -6px;
  bottom: -6px;
}

.outer-drag-handle .drag-handle-bar {
  background: rgba(255, 255, 255, 0.95);
  border: 2px solid #409eff;
  box-shadow: 0 0 6px rgba(64, 158, 255, 0.5);
}

.inner-drag-handle {
  top: -2px;
  bottom: -2px;
}

.inner-drag-handle .drag-handle-bar {
  background: rgba(255, 255, 255, 0.9);
  border: 1.5px solid #e6a23c;
  box-shadow: 0 0 4px rgba(230, 162, 60, 0.5);
}

.inner-drag-handle:hover .drag-handle-bar {
  background: #e6a23c;
  box-shadow: 0 0 8px rgba(230, 162, 60, 0.6);
}

/* 商家内部说明 */
.merchant-detail {
  margin-top: 16px;
  padding: 12px 16px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #67c23a;
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.detail-color {
  width: 16px;
  height: 16px;
  border-radius: 3px;
  flex-shrink: 0;
}

.merchant-remain-color {
  background: #67c23a;
}

.salesman-color {
  background: #e6a23c;
}

.detail-text {
  font-size: 13px;
  color: #606266;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .proportion-visualization {
    padding: 16px;
  }

  .outer-progress-bar {
    height: 40px;
  }

  .progress-labels {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
  }

  .merchant-detail {
    flex-direction: column;
    gap: 12px;
  }
}
</style>
